import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Subject } from 'rxjs';
import { map, takeUntil } from 'rxjs/operators';
import { AppStoreModule } from '@store/index';
import { select, Store } from '@ngrx/store';
import { findIndex } from '@utils/array';
import { NzMessageService } from 'ng-zorro-antd';
import { SongService } from '@services/song.service';
import { MemberService } from '@services/member.service';
import { BatchActionsService } from '@store/batch-actions.service';
import { getCurrentSong, getPlayer } from '@store/selectors/player.selector';
import { Singer, Song, SongSheet } from '@services/data-types/common.type';
import { ShareInfo } from '@store/reducers/member.reducer';
import { StorageService } from '@services/storage.service';
import { User } from '@services/data-types/member.type';


@Component({
  selector: 'app-sheet-info',
  templateUrl: './sheet-info.component.html',
  styleUrls: ['./sheet-info.component.less']
})
export class SheetInfoComponent implements OnInit, OnDestroy {
  sheetInfo: SongSheet;
  // 歌单详情描述信息
  description = {
    long: '',
    short: ''
  };
  controlDesc = {
    isExpand: false,
    label: '展开',
    iconCls: 'down'
  };
  user: User;
  currentSong: Song;
  currentIndex: number;
  private destroy$ = new Subject<void>();
  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private store$: Store<AppStoreModule>,
    private songServe: SongService,
    private nzMessageServe: NzMessageService,
    private memberService: MemberService,
    private storageService: StorageService,
    private batchActionsService: BatchActionsService
  ) {
    this.route.data.pipe(map(res => res.sheetInfo)).subscribe(res => {
      this.sheetInfo = res;
      if (res.description) {
        this.changeDesc(res.description);
      }
      this.listenCurrentSong();
    });
  }

  ngOnInit() {
    this.getUserInfo();
  }
  private replaceStr(str: string): string {
    return '<b>介绍：</b>' + str.replace(/\n/g, '<br />');
  }
  private listenCurrentSong() {
    this.store$.pipe(select(getPlayer), select(getCurrentSong), takeUntil(this.destroy$))
    .subscribe(song => {
      this.currentSong = song;
      if (song) {
        this.currentIndex = findIndex(this.sheetInfo.tracks, song);
      } else {
        this.currentIndex = -1;
      }
    });
  }
  private getUserInfo() {
    const userId = this.storageService.getStorage('wyyUserId');
    if (userId) {
      this.batchActionsService.setUserId(userId.toString());
      this.memberService.getUserDetail(userId).subscribe(res => {
        this.user = res;
      });
    }
  }
  // 收藏歌单
  onLikeSongSheet(id: string) {
    // 用户未登录
    if (!this.user) {
      this.batchActionsService.controlModalVisible(true, 'loginByPhone');
      return;
    }
    this.memberService.likeSongSheet(id).subscribe(() => {
      this.alertMessage('success', '已收藏');
    }, error => {
      this.alertMessage('error', error.msg || '收藏失败');
    });
  }
  // 收藏歌曲
  onLikeSong(id: string) {
    this.batchActionsService.likeSong(id);
    this.batchActionsService.controlModalVisible(true);
  }
  // 分享歌曲/歌单
  onShare(resource: Song | SongSheet, type = 'song') {
    let txt = '';
    if (type === 'playlist') {
      txt = this.makeTxt('歌单', resource.name, (resource as SongSheet).creator.nickname);
    } else {
      txt = this.makeTxt('歌曲', resource.name, (resource as Song).ar);
    }
    const info: ShareInfo = {id: resource.id.toString(), type, txt};
    this.batchActionsService.setShareInfo(info);
  }
  changeDesc(desc: string) {
    if (desc.length < 100) {
      this.description = {
        short: this.replaceStr(desc),
        long: ''
      };
    } else {
      this.description = {
        short: this.replaceStr(desc.slice(0, 100)) + '...',
        long: this.replaceStr(desc)
      };
    }
  }
  toggleDesc() {
    this.controlDesc.isExpand = !this.controlDesc.isExpand;
    if (this.controlDesc.isExpand) {
      this.controlDesc.iconCls = 'up';
      this.controlDesc.label = '收起';
    } else {
      this.controlDesc.iconCls = 'down';
      this.controlDesc.label = '展开';
    }
  }
  // 添加一首歌曲到歌曲列表
  onAddSong(song: Song, isPlay = false) {
    if (!this.currentSong || song.id !== this.currentSong.id) {
      this.songServe.getSongList(song).subscribe(list => {
        // 如果当前歌曲没有url，就不再执行insertSong这个Action
        if (list.length) {
          this.batchActionsService.insertSong(list[0], isPlay);
        } else {
          this.alertMessage('warning', '无url');
        }
      });
    }
  }
  // 添加歌曲列表到歌单
  onAddSongList(songs: Song[], isPlay = false) {
    this.songServe.getSongList(songs).subscribe(list => {
      if (list.length) {
        if (isPlay) {
          this.batchActionsService.selectPlayList({ list, index: 0 });
        } else {
          this.batchActionsService.insertSongList(list);
        }
      }
    });
  }
  skipToSinger(path: string, id: string) {
    if (this.user) {
      this.router.navigate([path, id]).then();
    } else {
      this.nzMessageServe.create('error', '请先登录');
    }
  }
  private makeTxt(type: string, name: string, makeBy: string | Singer[]): string {
    let needText = '';
    if (Array.isArray(makeBy)) {
      needText = makeBy.map(item => item.name).join('/');
    } else {
      needText = makeBy;
    }
    return `${type}: ${name} -- ${needText}`;
  }
  private alertMessage(type: string, content: string) {
    this.nzMessageServe.create(type, content);
  }
  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
}
